package com.webserver.core;

import com.webserver.annotations.Controller;
import com.webserver.annotations.RequestMapping;
import com.webserver.controller.UserController;
import com.webserver.http.HttpServletRequest;
import com.webserver.http.HttpServletResponse;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

public class DispatcherServlet {
    private static DispatcherServlet instance = new DispatcherServlet();
    private static File rootDir;
    private static File staticDir;

    static {
        try {
            rootDir = new File(DispatcherServlet.class.getClassLoader()
                    .getResource(".").toURI()
            );
            staticDir = new File(rootDir, "static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    private DispatcherServlet() {
    }

    public static DispatcherServlet getInstance() {
        return instance;
    }

    public void service(HttpServletRequest request, HttpServletResponse response) {
        String path = request.getRequestURI();
        try {
            Method method = HandlerMapping.getMethod(path);
            if(method!=null){
                Class cls = method.getDeclaringClass();
                Object controller = cls.newInstance();
                method.invoke(controller,request,response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        File file = new File(staticDir, path);
        if (file.isFile()) {
            response.setContentFile(file);
            response.addHeader("Server","BriWebServer");
        } else {
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            file = new File(staticDir, "/root/404.html");
            response.setContentFile(file);


        }
    }
}


